#include <iostream>
using namespace std;
#include <vector>
#include <queue>
const int N = 5e5 + 5;

typedef pair<int, int> Ppi;
vector<Ppi> e[N];
int d[N], vis[N];//d[u]表示，u与圈外邻点的距离最小
int ans, count;
#define inf 0x3f3f3f3f
int n, m;

int Prim(int s)
{
	//先全部初始化
	for (int i = 0; i <= n; i++)
		d[i] = inf;
	d[s] = 0;
	
	//依次枚举次数
	for (int i = 1; i <= n; i++)
	{
		int u = 0;
		//依次遍历每个点，找到最小距离的那个点
		for (int j = 1; j <= n; j++)
		{
			if (!vis[j] && d[j] < d[u]) u = j;
		}
		
		vis[u] = 1;
		ans += d[u];
		if (d[u] != inf) count++;
		
		//依次遍历u的每个邻边
		for (auto ed : e[u])
		{
			int v = ed.first, w = ed.second;
			if (d[v] > w) d[v] = w;
		}
	}
	return count == n;
}

priority_queue<Ppi> q;
int Prim_q(int s)
{
	for (int i = 0; i <= n; i++)
	{
		d[i] = inf;
	}
	d[s] = 0;
	q.push({0, s});
	
	while (q.size())
	{
		auto t = q.top();
		q.pop();
		int u = t.second;
		if (vis[u]) continue;
		vis[u] = 1;
		ans += d[u];
		if (d[u] != inf) count++;
		for (auto ed : e[u])
		{
			int v = ed.first, w = ed.second;
			if (d[v] > w)
			{
				d[v] = w;
				q.push({-d[v], v});
			}
		}
	}
	return count == n;
}
int main()
{
	cin >> n >> m;
	
	//构建无向图
	int a, b, c;
	for (int i = 1; i <= m; i++)
	{
		cin >> a >> b >> c;
		e[a].push_back({b, c});
		e[b].push_back({a, c});
	}
	
//	if (!Prim(1)) cout << "-1";
//	else cout << ans;
	
	if (!Prim_q(1)) cout << "-1";
	else cout << ans;
	return 0;
}
/*
5 7
1 2 2
1 3 1
1 4 2
2 3 1
2 5 3
3 4 3
3 5 6
*/